<?php


/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * @package	
 */
class HelpDeskHelperField {

	/**
	 * Returns a cleaned title
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &cleanTitle( $fieldtitle, $length='25' ) {

		// trim whitespace
		$trim_title = strtolower( trim( str_replace( " ", "", $fieldtitle ) ) );
		
		// strip all html tags
		$wc = strip_tags($trim_title);
		
		// remove 'words' that don't consist of alphanumerical characters or punctuation
		$pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
		$wc = trim(preg_replace($pattern, "", $wc));
		
		// remove one-letter 'words' that consist only of punctuation
		$wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", "", $wc));
		
		// remove superfluous whitespace
		$wc = preg_replace("/\s\s+/", "", $wc);		
		
		// cut title to length
		$cut_title = substr($wc, 0, $length);
		
		$data = $cut_title;
		
		return $data;
	}

	/**
	 * Returns a list of types
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &getFieldTypes( ) 
	{
		$types = array();
		$return = array();
		
		$types['1'] = "TEXT";
		$types['2'] = "TEXTAREA";
		$types['3'] = "SELECTLIST";
		$types['4'] = "RADIOLIST";
		$types['5'] = "CHECKBOX";
		$types['6'] = "DATE";
		// $types['7'] = "FILE";
		$types['8'] = "SEPARATOR";
		
		foreach ($types as $id=>$title) {
			$type = new stdClass();	
			$type->id = $id;
			$type->title = $title;
			$return[] = $type;
		}
		
		return $return;
	}
	
	/**
	 * 
	 * @param $default
	 * @param $exception
	 * @return unknown_type
	 */
	function getSelectListFieldTypes( $field, $default='', $options='' ) 
	{
		static $list; 
		
		if (empty($list)) 
		{
			$types = array();
			$items = HelpDeskHelperField::getFieldTypes();
			$types[] = HelpDeskHTML::selectOption( '', '- '.HelpDeskText::_( 'Select from List' ).' -' );
			if ($items) { foreach ($items as $item) {
				$types[] = HelpDeskHTML::selectOption( $item->id, HelpDeskText::_( $item->title ) );
			} }
			$list = HelpDeskHTML::genericList( $types, $field, $options, "value", "text", $default );
		
		}

		return $list;
	}

	/**
	 * Returns HTML
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &draw( $field, $control_name='params', $default=null ) {
		$return = HelpDeskHelperField::display( $field, $control_name, $default );
		return $return;
	}

	/**
	 * Returns HTML
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &display( $field, $control_name='params', $default=null ) {
		global $database;
		$success = false;
		$return = "";

		
		if (!is_object($field)) {
			if (is_numeric($field)) {
				// try to grab it
				// HelpDeskTable::addIncludePath( JPATH_COMPONENT_ADMINISTRATOR.DS.'tables'.DS );
				unset($table);
				$table = HelpDeskObject::getTable( 'Fields' );
				$table->load( $field );
				if (!$table->id) { return $success; }
				$field = $table;
			} else {
				return $success;
			}
		}
		
		if (!isset($field->typeid)) { return $success; }
				
		switch ($field->typeid) {
			case "1": // TEXT
				$size = $field->size ? 'size="'.$field->class.'"' : "";
				$class = $field->class ? 'class="'.$field->class.'"' : 'class="text_area"';
				$value = $default ? $default : $field->default;
				$return = '<input type="text" name="'.$control_name.'['.$field->db_fieldname.']" id="'.$control_name.$field->db_fieldname.'" value="'.$value.'" '.$class.' '.$size.' />';
			  break;
			case "2": // TEXTAREA
				$class = $field->class ? 'class="'.$field->class.'"' : 'class="text_area"';
				$value = $default ? $default : $field->default;
				$value = str_replace('<br />', "\n", $value);
				$return = '<textarea name="'.$control_name.'['.$field->db_fieldname.']" cols="'.$field->cols.'" rows="'.$field->rows.'" '.$class.' id="'.$control_name.$field->db_fieldname.'" >'.$value.'</textarea>';
			  break;
			case "3": // SELECTLIST
				$class = $field->class ? 'class="'.$field->class.'"' : 'class="text_area"';
				$value = $default ? $default : $field->default;
				$paramsObject = new mosParameters( $field->options );
				$params = $paramsObject->toArray();
				$options = array();
				if (is_array($params)) { foreach ($params as $val=>$text) {
					$options[] = mosHTML::makeOption( $val, HelpDeskText::_($text));
				} }
				$return = mosHTML::selectList( $options, ''.$control_name.'['.$field->db_fieldname.']', $class, 'value', 'text', $value, $control_name.$field->db_fieldname);
			  break;
			case "4": // RADIOLIST
				$class = $field->class ? 'class="'.$field->class.'"' : 'class="text_area"';
				$value = $default ? $default : $field->default;
				$paramsObject = new mosParameters( $field->options );
				$params = $paramsObject->toArray();
				$options = array();
				if (is_array($params)) { foreach ($params as $val=>$text) {
					$options[] = mosHTML::makeOption( $val, HelpDeskText::_($text));
				} }
				$return = mosHTML::radioList( $options, ''.$control_name.'['.$field->db_fieldname.']', $class, 'value', 'text', $value, $control_name.$field->db_fieldname);
			  break;
			case "5": // CHECKBOX
				$size = $field->size ? 'size="'.$field->class.'"' : "";
				$class = $field->class ? 'class="'.$field->class.'"' : 'class="text_area"';
				$value = $default ? $default : $field->default;
				$return = '<input type="checkbox" name="'.$control_name.'['.$field->db_fieldname.']" id="'.$control_name.$field->db_fieldname.'" value="'.$value.'" '.$class.' '.$size.' />';
			  break;
			case "6": // DATE
				mosCommonHTML::loadCalendar();
				$size = $field->size ? 'size="'.$field->class.'"' : "";
				$value = $default ? $default : $field->default;
				$class = $field->class ? $field->class : 'inputbox';
				$onclick = "onclick=\"return showCalendar('".$control_name."[".$field->db_fieldname."', 'y-mm-dd');\"";
				$return = '<input type="text" name="'.$control_name.'['.$field->db_fieldname.']" id="'.$control_name.$field->db_fieldname.'" value="'.$value.'" '.$class.' '.$size.' />';
                $return.= '<input type="reset" class="button" value="'.HelpDeskText::_('Select Date').'" '.$onclick.' />';
				// $return = JHTML::_('calendar', $value, $control_name.'['.$field->db_fieldname.']', $control_name.$field->db_fieldname, '%Y-%m-%d', array('class' => $class));
			  break;
			case "7": // FILE
				$value = $default ? $default : $field->default;
				$return = "";
			  break;
			case "8": // SEPARATOR
				$value = $default ? $default : $field->default;
				$class = $field->class ? 'class="'.$field->class.'"' : 'class=""';
				if ($value) {
					$return = '<div '.$class.'>'.$value.'</div>';
				} else {
					$return = '<hr '.$class.'/>';
				}
			  break;
			default:
				return $success;
			  break;		  
		}
		
		$success = true;
		return $return;		
	}

	/**
	 * Returns Value
	 * @param object 
	 * @param mixed value
	 * @return array
	 */
	function &displayValue( $field, $value ) {
		$success = false;
		$return = "";

		if (!is_object($field)) {
			if (is_numeric($field)) {
				// try to grab it
				// HelpDeskTable::addIncludePath( JPATH_COMPONENT_ADMINISTRATOR.DS.'tables'.DS );
				unset($table);
				$table = HelpDeskObject::getTable( 'Fields' );
				$table->load( $field );
				if (!$table->id) { return $success; }
				$field = $table;
			} else {
				return $success;
			}
		}
		
		if (!isset($field->typeid)) { return $success; }
				
		// if the field has options, find the title for the appropriate value
		// otherwise, if the value exists, return it
		// otherwise, return null
		switch ($field->typeid) {
			case "7": // FILE
				return $return;
			  break;
			case "3": // SELECTLIST
			case "4": // RADIOLIST
				$paramsObject = new mosParameters( $field->options );
				$params = $paramsObject->toArray();
				$options = array();
				if (is_array($params)) { foreach ($params as $val=>$text) {
					if ($val == $value) { $return = HelpDeskText::_($text); }
				} }
			  break;
			case "1": // TEXT
			case "2": // TEXTAREA
			case "5": // CHECKBOX
			case "6": // DATE
			case "8": // SEPARATOR
			default:
				$return = $value ? $value : "";
			  break;
		}		
		
		return $return;
	}
		
	/**
	 * Returns a list of types
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &getFieldTypeTitle( $id ) {
		$return = "";
		
		$types = &HelpDeskHelperField::getFieldTypes();
		foreach ($types as $t) {
			if ( $t->id == $id ) { $return = HelpDeskText::_( $t->title ); }
		}

		return $return;
	}

	/**
	 * 
	 * @param $id
	 * @return unknown_type
	 */
	function getCategories( $id )
	{
		$database = HelpDeskConfig::getDBO();

		$cat_query = " AND db.fieldid = '".$id."' ";
			
		$query = "
			SELECT 
				c.*, db.* 
			FROM 
				#__helpdesk_f2c AS db
				LEFT JOIN #__helpdesk_categories AS c ON c.id = db.categoryid
			WHERE 1
				{$cat_query}
		";

		$database->setQuery( $query );
		$data = $database->loadObjectList();
		
		return $data;
	}
	
	/**
	 * Returns an array of objects
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &getFieldCategories( $id ) 
	{
		$data = HelpDeskHelperField::getCategories( $id );
		return $data;
	}
	
	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function isFieldCategory( $fieldid, $catid ) 
	{
		$success = false;
		$data = &HelpDeskHelperField::getFieldCategories( $fieldid );

		for ($i=0; $i<count($data); $i++) {
			if ($data[$i]->id == $catid) { $success = true; }
		}

		return $success;	
	}

	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &addToCategory( $fieldid, $catid ) {
		$success = false;
		$database = HelpDeskConfig::getDBO();
		
	  	$query = " INSERT INTO #__helpdesk_f2c "
				." SET `categoryid` = '{$catid}', "
				." `fieldid` = '{$fieldid}' "
				;
		$database->setQuery( $query );
		if ($database->query()) { $success = true; }
		
		return $success;		
	}

	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &removeFromCategory( $fieldid, $catid ) {
		$success = false;
		$database = HelpDeskConfig::getDBO();
		
		$query = " DELETE FROM #__helpdesk_f2c "
				." WHERE `categoryid` = '$catid' "
				." AND `fieldid` = '$fieldid' "
				;
		$database->setQuery( $query );
		if ($database->query()) { $success = true; }
		
		return $success;		
	}

	/**
	 * Returns a field object
	 * from a db_fieldname
	 * 
	 * @return 
	 * @param $fieldname Object
	 */
	function getFromFieldname( $db_fieldname )
	{
		$success = false;
		$database = HelpDeskConfig::getDBO();
		
		$query = "
			SELECT 
				*
			FROM 
				#__helpdesk_fields
			WHERE
				LOWER( `db_fieldname` ) = LOWER( '{$db_fieldname}' )
			LIMIT 1
		";
		$database->setQuery( $query );
		if ( $data = $database->loadObject() ) { $success = $data; }
		
		return $success;
	}
	
	/**
	 * 
	 * @return 
	 * @param $fieldid Object
	 * @param $catid Object
	 */	
	function isRequired( $fieldid, $categoryid, $returnObject='' )
	{
		$success = false;
		$database = HelpDeskConfig::getDBO();
		
		$query = "
			SELECT 
				*
			FROM 
				#__helpdesk_f2c
			WHERE
				`fieldid` = '{$fieldid}'
			AND 
				`categoryid` = '{$categoryid}'
			LIMIT 1
		";
		$database->setQuery( $query );
		$data = $database->loadObject();
		if (isset($data->required) && intval($data->required) == '1' ) { 
			$success = true; 
		}
		
		if ($returnObject == '1') {
			$success = $data;
		}
		
		return $success;		
	}

	/**
	 * 
	 * @return 
	 * @param $fieldid Object
	 * @param $catid Object
	 */	
	function setRequired( $fieldid, $categoryid, $required='1' )
	{
		$success = false;
		$database = HelpDeskConfig::getDBO();
		
		$query = "
			UPDATE 
				#__helpdesk_f2c
			SET 
				`required` = '{$required}'
			WHERE
				`fieldid` = '{$fieldid}'
			AND 
				`categoryid` = '{$categoryid}'
			LIMIT 1
		";
		$database->setQuery( $query );
		if ( $database->query() ) { $success = true; }
		
		return $success;		
	}
				
}

?>